package service

import (
	"fmt"
	"hy_808/di"
	"hy_808/global"
	"time"
)

var SqlSel = "SELECT phone,device_no,token_code FROM hy_device with(nolock)"

func GetRowByPhone(phone string) (dataDb global.DeviceDBData, err error) {
	db := di.TakeDB()
	logger := di.Logdot()
	sqlStr := fmt.Sprintf("SELECT phone,device_no,token_code FROM hy_device with(nolock) where phone = '%s'", phone)
	rows, err := db.Query(sqlStr)
	if err != nil {
		logger.Error("查询设备失败", err)
		return
	}
	if len(rows) > 0 {
		dataDb.Phone = rows[0].Get("phone").String()
		dataDb.TokenCode = rows[0].Get("token_code").String()
		dataDb.DeviceId = rows[0].Get("device_id").String()
		dataDb.DeviceNo = int(rows[0].Get("device_no").Int())
	}
	return
}

func SaveDeviceToDB(phone string, busNo uint32, tokenCode string) {
	db := di.Sqlite()
	logger := di.Logdot()
	now := time.Now().Local().Format("2006-01-02 15:04:05")
	sqlStr := fmt.Sprintf(`INSERT INTO hy_device(phone,device_no,token_code,created_at,updated_at) VALUES ('%s',%d,'%s','%s','%s')`, phone, busNo, tokenCode, now, now)
	_, err := db.Exec(sqlStr)
	if err != nil {
		logger.Error("新增数据失败", err)
	}

}
